package com.android.functionmanagement.util;

import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class StepOpenHelper extends SQLiteOpenHelper {
	private static final String TAG = "StepOpenHelper";
	private static StepOpenHelper INSTANCE;
	public static final String KEY_DATE = "date";
	public static final String KEY_SETPS = "steps";
	public static final String KEY_ID = "_id";
	public static final String DATABASE_NAME = "step_database.db";
	public static final String DATABASE_TABLE = "step";
	
	public static final String KEY_TIMEMILLS = "timemills";
	public static final String DATABASE_TABLE_BUFFER = "stepbuffer";
	
	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_CREATE = "create table step (_id integer primary key autoincrement, "
			+ "steps integer not null, date date not null);";
	private static final String DATABASE_CREATE_TABLE_BUFFER = "create table stepbuffer (_id integer primary key autoincrement, "
			+ "steps integer not null, timemills integer not null);";
	private SQLiteDatabase mDatabase;

	public static StepOpenHelper getInstance(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new StepOpenHelper(context);
		}
		return INSTANCE;
	}

	StepOpenHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		mDatabase = db;
		db.execSQL(DATABASE_CREATE);
		db.execSQL(DATABASE_CREATE_TABLE_BUFFER);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS health");
		onCreate(db);
	}

	public int getStepCount(String date) {
		int step = 0;
		final SQLiteDatabase database = getWritableDatabase();
		try {
			synchronized(database){
				Cursor cursor = database.query(DATABASE_TABLE, new String[] { KEY_DATE, KEY_SETPS }, "date=?",
						new String[] { date }, null, null, null);
				if ((cursor != null) && (cursor.getCount() > 0)) {
					cursor.moveToFirst();
					step = cursor.getInt(cursor.getColumnIndex(KEY_SETPS));
				}
				if (cursor != null) {
					cursor.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if ((database != null)&&(database.isOpen())) {
				database.close();
			}
		}
		return step;
	};
	
	public void update(int steps, String date) {
		SQLiteDatabase database = getWritableDatabase();
		try {
			synchronized(database){
				Cursor cursor = database.query(StepOpenHelper.DATABASE_TABLE,
						new String[] {StepOpenHelper.KEY_DATE, StepOpenHelper.KEY_SETPS }, "date=?",
						new String[] { date }, null, null, null);
				if (cursor != null && cursor.getCount() > 0) {
					cursor.moveToFirst();
					ContentValues values = new ContentValues();
					if(steps > cursor.getInt(cursor.getColumnIndex(KEY_SETPS))) {
						values.put(KEY_SETPS, steps);
						database.update(DATABASE_TABLE, values, "date=?", new String[] { date });
					}
				} else {
					ContentValues initialValues = new ContentValues();
					initialValues.put(StepOpenHelper.KEY_DATE, date);
					initialValues.put(StepOpenHelper.KEY_SETPS, steps);
					database.insert(StepOpenHelper.DATABASE_TABLE, null, initialValues);
				}
				if (cursor != null) {
					cursor.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if ((database != null)&&(database.isOpen())) {
				database.close();
			}
		}
	}
	
	//====================================================
	
	public long insertStepBuffer(int steps, Long timeMills) {
		SQLiteDatabase database = getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(KEY_TIMEMILLS, timeMills);
		values.put(KEY_SETPS, steps);
		try {
			synchronized(database){
				long id = database.insert(DATABASE_TABLE_BUFFER, null, values);
				return id;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if ((database != null)&&(database.isOpen())) {
				database.close();
			}
		}
		return -1;
	}
	
	public void deleteStepBuffer() {
		SQLiteDatabase database = getWritableDatabase();
		try {
			database.delete(DATABASE_TABLE_BUFFER, null, null);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if ((database != null)&&(database.isOpen())) {
				database.close();
			}
		}
	}
	
	public HashMap<Long, Integer> getStepBufferHashMap() {
		final SQLiteDatabase database = getWritableDatabase();
		HashMap<Long, Integer> stepMaps = new HashMap<Long, Integer>();
		
		try {
			synchronized(database){
				Cursor cursor = database.rawQuery("Select * From " + DATABASE_TABLE_BUFFER, null);
				if (cursor != null && cursor.getCount() > 0) {
					while(cursor.moveToNext())
					{
						Integer steps = cursor.getInt(cursor.getColumnIndex(KEY_SETPS));
						Long timeMillis = cursor.getLong(cursor.getColumnIndex(KEY_TIMEMILLS));
						stepMaps.put(timeMillis, steps);
					}
				}
				if (cursor != null) {
					cursor.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if ((database != null)&&(database.isOpen())) {
				database.close();
			}
		}
		
		if ((stepMaps != null)&&(stepMaps.size()>0)) {
			return stepMaps;
		}
		
		return null;
	}
	
	public int getStepBufferCount() {
		SQLiteDatabase database = getWritableDatabase();
		int count = 0;
		
		try {
			synchronized(database){
				Cursor cursor = database.rawQuery("Select * From " + DATABASE_TABLE_BUFFER, null);
				if (cursor != null) {
					count = cursor.getCount();
					cursor.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if ((database != null)&&(database.isOpen())) {
				database.close();
			}
		}
		
		return count;
	}
	
	public void close(){
		if ((mDatabase != null)&&(mDatabase.isOpen())) {
			mDatabase.close();
		}
	}
}
